/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-10 09:20:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-09 22:00:51
 * @FilePath: \work-tool\my-dev-project\src\views\system\menu.tsx
 * @Description: 菜单管理页面
 */
import React, { useState, useEffect } from 'react';
import { Card, Tree, Button, Input, Modal, Form, Select, message, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';


const { Option } = Select;
const { confirm } = Modal;

// 模拟菜单数据
const mockMenuData = [
  {
    key: 'dashboard',
    title: '控制台',
    route: '/dashboard',
    order: 1,
    parentKey: '',
    icon: 'DashboardOutlined',
  },
  {
    key: 'system',
    title: '系统管理',
    route: '/system',
    order: 2,
    parentKey: '',
    icon: 'SettingOutlined',
  },
  {
    key: 'system:user',
    title: '用户管理',
    route: '/system/user',
    order: 1,
    parentKey: 'system',
    icon: 'UserOutlined',
  },
  {
    key: 'system:menu',
    title: '菜单管理',
    route: '/system/menu',
    order: 2,
    parentKey: 'system',
    icon: 'MenuOutlined',
  },
  {
    key: 'system:role',
    title: '角色管理',
    route: '/system/role',
    order: 3,
    parentKey: 'system',
    icon: 'TeamOutlined',
  },
  {
    key: 'system:department',
    title: '部门管理',
    route: '/system/department',
    order: 4,
    parentKey: 'system',
    icon: 'HomeOutlined',
  },
  {
    key: 'order',
    title: '订单管理',
    route: '/order',
    order: 3,
    parentKey: '',
    icon: 'ShoppingOutlined',
  },
  {
    key: 'order:list',
    title: '订单列表',
    route: '/order/list',
    order: 1,
    parentKey: 'order',
    icon: 'OrderedListOutlined',
  },
  {
    key: 'order:aggregate',
    title: '订单聚合',
    route: '/order/aggregate',
    order: 2,
    parentKey: 'order',
    icon: 'BarChartOutlined',
  },
  {
    key: 'order:track',
    title: '订单追踪',
    route: '/order/track',
    order: 3,
    parentKey: 'order',
    icon: 'EnvironmentOutlined',
  },
];

interface MenuItem {
  key: string;
  title: string;
  route: string;
  order: number;
  parentKey: string;
  icon: string;
}

const MenuManagement: React.FC = () => {
  const [menuData, setMenuData] = useState<MenuItem[]>(mockMenuData);
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [editingMenu, setEditingMenu] = useState<MenuItem | null>(null);
  const [form] = Form.useForm();
  const [availableIcons] = useState<string[]>([
    'DashboardOutlined', 'SettingOutlined', 'UserOutlined', 'MenuOutlined',
    'TeamOutlined', 'HomeOutlined', 'ShoppingOutlined', 'OrderedListOutlined',
    'BarChartOutlined', 'EnvironmentOutlined', 'PieChartOutlined', 'LineChartOutlined',
    'CalendarOutlined', 'FileOutlined', 'FolderOutlined', 'MessageOutlined',
  ]);

  // 构建树形数据
  const buildTreeData = (menuItems: MenuItem[]): DataNode[] => {
    const roots = menuItems.filter(item => !item.parentKey);
    const buildChildren = (parentKey: string): DataNode[] => {
      return menuItems
        .filter(item => item.parentKey === parentKey)
        .sort((a, b) => a.order - b.order)
        .map(item => ({
          title: item.title,
          key: item.key,
          children: buildChildren(item.key),
        }));
    };

    return roots
      .sort((a, b) => a.order - b.order)
      .map(item => ({
        title: item.title,
        key: item.key,
        children: buildChildren(item.key),
      }));
  };

  // 获取父级菜单选项
  const getParentMenuOptions = (): { label: string; value: string }[] => {
    const options = menuData
      .filter(item => !item.parentKey || editingMenu?.key === item.parentKey)
      .map(item => ({ label: item.title, value: item.key }));
    return [{ label: '无父级菜单', value: '' }, ...options];
  };

  useEffect(() => {
    setTreeData(buildTreeData(menuData));
  }, [menuData]);

  // 处理节点选择
  const onSelect = (selectedKeys: string[]) => {
    setSelectedKeys(selectedKeys);
  };

  // 打开创建/编辑模态框
  const showModal = (menu?: MenuItem) => {
    if (menu) {
      setEditingMenu(menu);
      form.setFieldsValue(menu);
    } else {
      setEditingMenu(null);
      form.resetFields();
    }
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        if (editingMenu) {
          // 编辑菜单
          const updatedMenuData = menuData.map(item =>
            item.key === editingMenu.key ? { ...item, ...values } : item
          );
          setMenuData(updatedMenuData);
          message.success('菜单更新成功');
        } else {
          // 创建菜单
          const newMenu: MenuItem = {
            ...values,
            key: values.parentKey ? `${values.parentKey}:${values.key}` : values.key,
            order: parseInt(values.order.toString()),
          };
          setMenuData([...menuData, newMenu]);
          message.success('菜单创建成功');
        }
        setIsModalVisible(false);
        form.resetFields();
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  // 删除菜单
  const handleDelete = () => {
    if (!selectedKeys.length) {
      message.warning('请先选择要删除的菜单');
      return;
    }

    const keyToDelete = selectedKeys[0];
    // 检查是否有子菜单
    const hasChildren = menuData.some(item => item.parentKey === keyToDelete);

    if (hasChildren) {
      message.error('该菜单下有子菜单，无法删除');
      return;
    }

    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除该菜单吗？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        setMenuData(menuData.filter(item => item.key !== keyToDelete));
        setSelectedKeys([]);
        message.success('菜单删除成功');
      },
    });
  };

  // 处理拖拽
  // const onDrop = (info: { node: { key: string; props: { eventKey: string } }; dragNode: { key: string }; dropPosition: number }) => {

  //   const dropKey = info.node.key;
  //   const dragKey = info.dragNode.key;
  //   const dropPosition = info.dropPosition;
  //   const dragMenu = menuData.find(item => item.key === dragKey);

  //   if (!dragMenu) return;

  //   // 计算新的父级和顺序
  //   const newParentKey = info.node.props.eventKey;
  //   let newOrder = 0;

  //   if (dropPosition === -1) {
  //     // 拖到节点上
  //     const children = menuData.filter(item => item.parentKey === newParentKey);
  //     newOrder = children.length + 1;
  //   } else {
  //     // 拖到节点前后
  //     if (dropPosition === 0) {
  //       // 前面
  //       const siblings = menuData.filter(item => item.parentKey === info.node.props.eventKey);
  //       const targetIndex = siblings.findIndex(item => item.key === dropKey);
  //       newOrder = targetIndex + 1;
  //     } else {
  //       // 后面
  //       const siblings = menuData.filter(item => item.parentKey === info.node.props.eventKey);
  //       const targetIndex = siblings.findIndex(item => item.key === dropKey);
  //       newOrder = targetIndex + 2;
  //     }
  //   }

  //   // 更新菜单数据
  //   const updatedMenuData = menuData.map(item => {
  //     if (item.key === dragKey) {
  //       return {
  //         ...item,
  //         parentKey: newParentKey,
  //         order: newOrder,
  //       };
  //     }
  //     return item;
  //   });

  //   setMenuData(updatedMenuData);
  //   message.success('菜单排序更新成功');
  // };

  return (
    <div style={{ padding: 24 }}>
      <Card
        title="菜单管理"
        extra={
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
              添加菜单
            </Button>
            <Button icon={<EditOutlined />} onClick={() => {
              if (selectedKeys.length) {
                const selectedMenu = menuData.find(item => item.key === selectedKeys[0]);
                if (selectedMenu) showModal(selectedMenu);
              } else {
                message.warning('请先选择要编辑的菜单');
              }
            }}>
              编辑菜单
            </Button>
            <Button danger icon={<DeleteOutlined />} onClick={handleDelete}>
              删除菜单
            </Button>
          </Space>
        }
      >
        <Tree
          className="menu-tree"
          selectedKeys={selectedKeys}
          treeData={treeData}
          draggable
          onSelect={onSelect}
          onDrop={(info) => {
            const dropKey = info.node.key;
            const dragKey = info.dragNode.key;
            const dropPosition = info.dropPosition;
            const dragMenu = menuData.find(item => item.key === dragKey);

            if (!dragMenu) return;

            // 计算新的父级和顺序
            const newParentKey = info.node.key as string;
            let newOrder = 0;

            if (dropPosition === -1) {
              // 拖到节点上
              const children = menuData.filter(item => item.parentKey === newParentKey);
              newOrder = children.length + 1;
            } else {
              // 拖到节点前后
              if (dropPosition === 0) {
                // 前面
                const siblings = menuData.filter(item => item.parentKey === newParentKey);
                const targetIndex = siblings.findIndex(item => item.key === dropKey);
                newOrder = targetIndex + 1;
              } else {
                // 后面
                const siblings = menuData.filter(item => item.parentKey === newParentKey);
                const targetIndex = siblings.findIndex(item => item.key === dropKey);
                newOrder = targetIndex + 2;
              }
            }

            // 更新菜单数据
            const updatedMenuData = menuData.map(item => {
              if (item.key === dragKey) {
                return {
                  ...item,
                  parentKey: newParentKey,
                  order: newOrder,
                };
              }
              return item;
            });

            setMenuData(updatedMenuData);
            message.success('菜单排序更新成功');
          }}
          style={{ border: '1px solid #f0f0f0', borderRadius: '4px', padding: '16px' }}
        />
      </Card>

      {/* 创建/编辑菜单模态框 */}
      <Modal
        title={editingMenu ? "编辑菜单" : "创建菜单"}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={editingMenu || {
            parentKey: '',
            order: 1
          }}
        >
          <Form.Item
            name="parentKey"
            label="父级菜单"
            rules={[{ required: true, message: '请选择父级菜单' }]}
          >
            <Select placeholder="请选择父级菜单" allowClear>
              {getParentMenuOptions().map(option => (
                <Option key={option.value} value={option.value}>{option.label}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="key"
            label="菜单标识"
            rules={[
              { required: true, message: '请输入菜单标识' },
              { pattern: /^[a-zA-Z0-9_:]+$/, message: '菜单标识只能包含字母、数字、下划线和冒号' }
            ]}
          >
            <Input placeholder="请输入菜单标识" />
          </Form.Item>

          <Form.Item
            name="title"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>

          <Form.Item
            name="route"
            label="路由地址"
            rules={[{ required: true, message: '请输入路由地址' }]}
          >
            <Input placeholder="请输入路由地址" />
          </Form.Item>

          <Form.Item
            name="order"
            label="排序号"
            rules={[
              { required: true, message: '请输入排序号' },
              { type: 'number', min: 1, message: '排序号必须大于0' }
            ]}
          >
            <Input type="number" placeholder="请输入排序号" min={1} />
          </Form.Item>

          <Form.Item
            name="icon"
            label="图标"
            rules={[{ required: true, message: '请选择图标' }]}
          >
            <Select placeholder="请选择图标">
              {availableIcons.map(icon => (
                <Option key={icon} value={icon}>{icon}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                {editingMenu ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuManagement;